const curry = (fn, ...arr) => {
  let len = fn.length;
  return function (...args) {
    let newArgs = [...arr, ...args];
    if (newArgs.length < len) {
      return curry(fn, ...newArgs);
    }
    return fn(...newArgs);
  };
};
const currying = (fn) => {
  return function curriedFn(...args) {
    if(args.length < fn.length) {
      return function(){
        args = [...args, ...arguments];
        return curriedFn(...args);
      }
    }
    return fn(...args);
  }
};
let sum = (x, y, z) => x + y + z;
let c = currying(sum)(1, 3)(8);
console.log(c);

// 递归操作，如果数据量大，会有很大的内存占用
const fib = (n) => {
  if (n <= 2) return n;
  return fib(n - 1) + fib(n - 2);
};
console.log(fib(5));
// console.log(fib(45)); 占用大量内存
// fib(5) = fib(4) +                    fib(3)         =
//         fib(3) + fib(2)  +           fib(2) + fib(1) =
//         fib(2) + fib(1) + fib(2)  +   fib(2) + fib(1) =
//         2     + 1     + 2      +    2    +  1
// 普通递归会将随着层级增加，横向的参数展开的更多，每个参数都会占内存地址。

const fb = (n, res, prev) => {
  if (n < 1) return res;
  return fb(n - 1, prev, res + prev);
};
console.log(fb(5, 1, 1));
console.log(fb(45, 1, 1));
// 5 1 1
// 4 1 2
// 3 2 3
// 2 3 5
// 1 5 8
// 0 8 13 当0返回8，出结果
function tailrecsum(x, running_total = 0) {
  if (x === 0) {
    return running_total;
  } else {
    return tailrecsum(x - 1, running_total + x) + x;
  }
}

console.log(tailrecsum(150, 0));
// 5 0
// 4 5
// 3 9
// 2 12
// 1 14
// 0 15
